﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using System.Device.Location;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using ShakeGestures;
using System.Threading;

namespace egco380
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        double[] rate = new double[6];
        WebClient Newclient = new WebClient();
        GeoCoordinateWatcher watcher;
        public MainPage()
        {
            ShakeGesturesHelper.Instance.ShakeGesture += new
    EventHandler<ShakeGestureEventArgs>(Instance_ShakeGesture);

            // optional, set parameters
            ShakeGesturesHelper.Instance.MinimumRequiredMovesForShake = 2;
            weather_show();
            new_show();
            cur_rate();
            InitializeComponent();
          ShakeGesturesHelper.Instance.Active = true;
          ListBoxItem lst = (ListBoxItem)list_rate.SelectedItem;
           
          trans_result.Text = (String)lst.Content + " to Baht";
          }
        private void Instance_ShakeGesture(object sender, ShakeGestureEventArgs e)
        {


            Dispatcher.BeginInvoke(new ThreadStart(refresh));
        }
        private void refresh()
        {
            // load the twitter data
            WebClient Newclient = new WebClient();

            Newclient.DownloadStringAsync(new Uri("http://www.thairath.co.th/rss/feed1.xml" + "&r=" + Guid.NewGuid().ToString(), UriKind.RelativeOrAbsolute));
            Newclient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitterclient_DownloadStringCompleted);

        }

        void weather_show()
        {
            if (watcher == null)
            {
                watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High); // using high accuracy
                watcher.MovementThreshold = 20;
                watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
            } watcher.Start();
       
        }
        void new_show()
        {
            WebClient Newclient1 = new WebClient();
      
            Newclient1.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitterclient1_DownloadStringCompleted);
            Newclient1.DownloadStringAsync(new Uri("http://www.thairath.co.th/rss/feed1.xml", UriKind.RelativeOrAbsolute));
        }
        void twitterclient1_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            //throw new NotImplementedException();
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
                return;

            }


            XElement NewElement = XElement.Parse(e.Result);

            var items = from item in NewElement.Descendants("item")
                        select new @new
                        {
                            //  UserImage = item.Element("user").Element("profile_image_url").Value,
                            Text = item.Element("title").Value,
                            DateTime = item.Element("pubDate").Value.Replace("+0700", ""),
                            pageurl = item.Element("link").Value,
                            des = item.Element("description").Value
                        };

            lstTwitter.ItemsSource = items;
            for (int i = 0; i < items.Count(); i++)
            {
                temp.Add(items.ElementAt(i));
            }
        }
        void twitterclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            //throw new NotImplementedException();
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
                return;

            }

        
            XElement NewElement = XElement.Parse(e.Result);

            var items = from item in NewElement.Descendants("item")
                        select new @new
                        {
                          //  UserImage = item.Element("user").Element("profile_image_url").Value,
                            Text = item.Element("title").Value,
                            DateTime = item.Element("pubDate").Value.Replace("+0700", ""),
                            pageurl = item.Element("link").Value,
                            des = item.Element("description").Value                           
                        };
            
            lstTwitter.ItemsSource = items;
            for (int i = 0; i < items.Count(); i++)
            {
                temp.Add(items.ElementAt(i));
            }
        }
        List<@new> temp = new List<@new>();
        private void lstTwitter_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //ListBoxItem lst = (ListBoxItem)lstTwitter.SelectedItem;
            NavigationService.Navigate(new Uri("/resultnewpage.xaml?resultpage=" +temp[lstTwitter.SelectedIndex].pageurl+"&des="+temp[lstTwitter.SelectedIndex].des, UriKind.RelativeOrAbsolute));      
        	// TODO: Add event handler implementation here.
        }
        void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            WebClient lo = new WebClient();
             lo.DownloadStringCompleted += new DownloadStringCompletedEventHandler(lo_DownloadStringCompleted);
          
            int tem_lat= (int) e.Position.Location.Latitude;
            int tem_long =(int) e.Position.Location.Longitude;
            long latitude=  100000*tem_lat;
            long longtitue =100000* tem_long;

          
               
          
            lo.DownloadStringAsync(new Uri("http://www.google.com/ig/api?weather=,,," 
                +latitude+","
                +longtitue, UriKind.RelativeOrAbsolute));
          }

    

        void lo_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            XElement NewElement = XElement.Parse(e.Result);

            var cur_weather = from item in NewElement.Descendants("current_conditions")
                        select  new weather
                        {
                           condition = item.Element("condition").Attribute("data").Value,
                           temp_c = item.Element("temp_c").Attribute("data").Value                         
                        };
            cur_weather.Count();
        
            try
            {
 t_c.Text = cur_weather.ElementAt(0).temp_c;
                //set pic for weather
                string a= cur_weather.ElementAt(0).condition;
                string picpath = "sunny.png";

                if (a.CompareTo("Chance of Storm") == 0)
                {
                    picpath = "chance of storm.png";
                }

                else if (a.CompareTo("Mostly Sunny") == 0)
                {
                    picpath = "sunny.png";
                }

                else if (a.CompareTo("Cloudy") == 0 )
                {
                    picpath = "cloudy.png";
                }

                else if (a.CompareTo("Partly Cloudy") == 0)
                {
                    picpath = "partly cloudy.png";
                }

                else if (a.CompareTo("Mostly Cloudy") == 0)
                {
                    picpath = "mostly cloudy.png";
                }

                else if (a.CompareTo("Rainy") == 0)
                {
                    picpath = "rainy.png";
                }

                else if (a.CompareTo("Thunderstorm") == 0)
                {
                    picpath = "storm.png";
                }
                //StreamResourceInfo resourceInfo = Application.GetResourceStream(uri);
                //BitmapImage bmp = new BitmapImage();
                //bmp.SetSource(resourceInfo.Stream);
                img.Source = new BitmapImage(new Uri("pic/"+picpath, UriKind.RelativeOrAbsolute));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Turn on your Location service");
            }
               
            
           
            var fore_weather = from item in NewElement.Descendants("forecast_conditions")
                        select new fu_weather
                        {
                            condition = item.Element("condition").Attribute("data").Value,
                            l_temp = item.Element("low").Attribute("data").Value,
                            h_temp = item.Element("high").Attribute("data").Value,
                        }; if (fore_weather.Count() > 1)
            {
                float f_h = (Convert.ToInt32(fore_weather.ElementAt(0).h_temp) - 32);
                f_h = f_h * 5 / 9;
                int f_l = (Convert.ToInt32(fore_weather.ElementAt(0).l_temp) - 32);
                f_l = f_l * 5 / 9;

                tmr_c.Text = String.Format("{0:0}", f_l) + " - " + String.Format("{0:0}", f_h);
                //tmr_con.Text = fore_weather.ElementAt(0).condition;

                //set pic for weather
                string b = fore_weather.ElementAt(0).condition;
                string picpath1 = "sunny.png";

                if (b.CompareTo("Chance of Storm") == 0)
                {
                    picpath1 = "chance of storm.png";
                }

                else if (b.CompareTo("Mostly Sunny") == 0)
                {
                    picpath1 = "sunny.png";
                }

                else if (b.CompareTo("Cloudy") == 0)
                {
                    picpath1 = "cloudy.png";
                }

                else if (b.CompareTo("Partly Cloudy") == 0)
                {
                    picpath1 = "partly cloudy.png";
                }

                else if (b.CompareTo("Mostly Cloudy") == 0)
                {
                    picpath1 = "mostly cloudy.png";
                }

                else if (b.CompareTo("Rainy") == 0)
                {
                    picpath1 = "rainy.png";
                }

                else if (b.CompareTo("Thunderstorm") == 0)
                {
                    picpath1 = "storm.png";
                }
                //StreamResourceInfo resourceInfo = Application.GetResourceStream(uri);
                //BitmapImage bmp = new BitmapImage();
                //bmp.SetSource(resourceInfo.Stream);
                img1.Source = new BitmapImage(new Uri("pic/" + picpath1, UriKind.RelativeOrAbsolute));

            }
        }

    

        private void input_cal_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            double tmp=0.0;
            for (int i = 0; i < 6; i++)
			{
                if (rate[i]!=0.0)
                {
                    tmp++;
                }
               
			}
            if (tmp!=6.0)
            {
                MessageBox.Show("Service unavailable", "Message", MessageBoxButton.OK);
            }
            else
            {
                if (!input_cal.Text.Equals(""))
                {

                    ListBoxItem lst = (ListBoxItem)list_rate.SelectedItem;

                    if (trans.IsChecked == true)
                    {
                        result_cal.Text = String.Format("{0:F2}", (double.Parse(input_cal.Text) * double.Parse(rate.ElementAt(list_rate.SelectedIndex).ToString())));
                        trans_result.Text = "Baht to " + (String)lst.Content;

                    }
                    else
                    {
                        result_cal.Text = String.Format("{0:F2}", (double.Parse(input_cal.Text) / double.Parse(rate.ElementAt(list_rate.SelectedIndex).ToString())));
                        trans_result.Text = (String)lst.Content + " to Baht";
                    }
                 
                  //  type.Text = (String)lst.Content;
                }
                else { result_cal.Text = "0.0"; }
            }
        }

        private void list_rate_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            double tmp = 0.0;
            for (int i = 0; i < 6; i++)
            {
                if (rate[i] != 0.0)
                {
                    tmp++;
                }

            }
            if (tmp != 6.0)
            {
          //      MessageBox.Show("Service unavailable", "Message", MessageBoxButton.OK);
            }
            else
            {
                if (!input_cal.Text.Equals(""))
                {

                    ListBoxItem lst = (ListBoxItem)list_rate.SelectedItem;
                    if (trans.IsChecked == true)
                    {
                        result_cal.Text = String.Format("{0:F2}", (double.Parse(input_cal.Text) * double.Parse(rate.ElementAt(list_rate.SelectedIndex).ToString())));
                        trans_result.Text = "Baht to " + (String)lst.Content;

                    }
                    else
                    {
                        result_cal.Text = String.Format("{0:F2}", (double.Parse(input_cal.Text) / double.Parse(rate.ElementAt(list_rate.SelectedIndex).ToString())));
                        trans_result.Text = (String)lst.Content+" to Baht";

                    }
                   // type.Text = (String)lst.Content;
                }
                else
                {
                    ListBoxItem lst = (ListBoxItem)list_rate.SelectedItem;
            
                    result_cal.Text = "0.0";
                    if (trans.IsChecked == true)
                    {
                        trans_result.Text = "Baht to " + (String)lst.Content;

                    }
                    else
                    {
                        trans_result.Text = (String)lst.Content + " to Baht";
                    }
                }
            }
        }

        private void trans_Click(object sender, RoutedEventArgs e)
        {
            ListBoxItem lst = (ListBoxItem)list_rate.SelectedItem;
              
            if (trans.IsChecked == true)
            {
                trans_result.Text = "Baht to " + (String)lst.Content;
                result_cal.Text = String.Format("{0:F2}", (double.Parse(input_cal.Text) * double.Parse(rate.ElementAt(list_rate.SelectedIndex).ToString())));
                       
            }
            else
            {
                result_cal.Text = String.Format("{0:F2}", (double.Parse(input_cal.Text) / double.Parse(rate.ElementAt(list_rate.SelectedIndex).ToString())));                       
                trans_result.Text = (String)lst.Content + " to Baht";
            }
        }

     
          
     
   
    }

}